<template>
  <el-dialog title="添加日程" :visible.sync="dialogFormVisible" class="addsc">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item required label="日程标题" prop="title">
        <el-input v-model="form.title" />
      </el-form-item>

      <el-form-item label="日期" required>
        <el-col :span="11">
          <el-form-item prop="kssj">
            <el-date-picker
              v-model="form.kssj"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm"
              placeholder="开始时间"
              :picker-options="pickerOption"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col class="line" :span="2">-</el-col>
        <el-col :span="11">
          <el-form-item
            prop="jssj"
          ><el-date-picker
            v-model="form.jssj"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm"
            placeholder="结束时间"
            :picker-options="pickerOption"
            style="width: 100%"
          /></el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="是否公开" prop="sfgk" required>
        <el-switch v-model="form.sfgk" />
      </el-form-item>
      <el-form-item label="日程级别" prop="rcjb" required>
        <el-radio-group v-model="form.rcjb">
          <el-radio label="1">一般日程</el-radio>
          <el-radio label="2">重要日程</el-radio>
          <el-radio label="3">紧急日程</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 授权部分 准备用添加部门的方式 -->
      <el-form-item
        label="安排部门"
        prop="sysOrganizations"
        :class="organizationVisiable === false ? 'active' : ''"
      >
        <el-button
          type="primary"
          @click="
            dialogTransferVisible = true; //绑定多个方法时，要用分号做分隔号，且非表示式的方法一定要加小括号，不加不生效
            getDepts();
          "
        >
          部门授权
        </el-button>
        {{ DRHA_EFaultModeTree_lables }}
        <el-dialog
          :class="organizationVisiable === false ? 'active' : ''"
          title="部门授权"
          :visible.sync="dialogTransferVisible"
          append-to-body
        >
          <treeselect
            v-model="treeValue"
            :options="depts"
            :multiple="true"
            :flat="true"
            :load-options="loadDepts"
            style="width: 178px"
            placeholder="选择部门"
            @select="DRHA_EFaultModeTree_handleSelect"
            @deselect="DRHA_EFaultModeTree_handleDeSelect"
          />

          <div>您授权的部门为：{{ DRHA_EFaultModeTree_lables }}</div>
          <!-- <div>{{ JSON.stringify(depts) }}</div> -->
          <!-- <treeTransfer
            ref="treeTransfer"
            :datas="depts"
            :defaultProps="defaultProps"
          ></treeTransfer>
          <div slot="title">{{ nameTest }}</div> -->
        </el-dialog>
      </el-form-item>

      <el-form-item
        label="安排人员"
        prop="sysUserMembers"
        :class="organizationVisiable === false ? 'active' : ''"
      >
        <el-button type="primary" @click="dialogUserTransferVisible = true">
          用户授权
        </el-button>
        <el-dialog
          title="用户授权"
          :visible.sync="dialogUserTransferVisible"
          append-to-body
        >
          <el-row style="padding-top: 20px;">
            <el-col span="12">
              <el-input
                v-model="usersValue"
                placeholder="请输入搜索关键字"
                class="input-with-select"
                size="small"
              >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="filterChange"
                />
              </el-input>
            </el-col>
          </el-row>

          <!-- :filterable="true"
            :filter-method="filterMethod"
            filter-placeholder="请输入用户名或userid" -->
          <el-transfer v-model="usersValue" :data="currentPageDatas">
            <el-pagination
              slot="left-footer"
              small
              :page-size.sync="page.pageSize"
              :page-count="5"
              :total="page.total"
              :current-page.sync="page.pageNo"
              style="margin-top: 8px;"
              layout="prev, pager, next"
              @current-change="handleCurrentChangeHandler"
            /></el-transfer>
          <div slot="footer">
            <!-- 有表单提交，需要验证输入，所以使用自定底部按钮 -->
            <el-button
              type="text"
              @click="dialogUserTransferVisible = false"
            >取消</el-button>
            <el-button type="primary" @click="addSchedule">确定</el-button>
          </div>
        </el-dialog>
      </el-form-item>
      <el-form-item label="日程描述" prop="content" required>
        <el-input v-model="form.content" type="textarea" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取消</el-button>
      <el-button @click="resetForm('form')">重置</el-button>
      <el-button type="primary" @click="addSchedule('form')">确定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { saveSchedule } from '@/api/schedule/schedule'
import { getDepts } from '@/api/system/dept'
// import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
// import treeTransfer from '@/views/components/TreeTransfer.vue'

import CRUD, { presenter, header, crud } from '@crud/crud'
import crudUser from '@/api/system/user'
// import rrOperation from '@crud/RR.operation' // 搜索
// import pagination from '@crud/Pagination' // 分页

export default {
  name: 'AddSchedule',
  /*   components: { treeTransfer, Treeselect, rrOperation, pagination }, */

  cruds() {
    return CRUD({
      title: '用户',
      url: 'rest/api/user',
      crudMethod: { ...crudUser }
    })
  },
  mixins: [presenter(), header(), crud()],

  data() {
    // 日期验证
    var validateDate = (rule, endTime, callback) => {
      // 验证日期（判断结束日期是否大于开始日期）日期格式为YY—MM—DD
      var startTime = this.form.kssj
      if (!endTime) {
        return callback(new Error('结束时间不能为空'))
      }
      setTimeout(() => {
        if (startTime.length > 0 && endTime.length > 0) {
          // var startTmp = startTime.split("-");
          // var endTmp = endTime.split("-");
          // var sd = new Date(startTmp[0], startTmp[1], startTmp[2]);
          // var ed = new Date(endTmp[0], endTmp[1], endTmp[2]);
          var sd = new Date(startTime)
          var ed = new Date(endTime)

          if (sd.getTime() > ed.getTime()) {
            callback(new Error('开始日期不能大于结束日期'))
          } else {
            callback()
          }
        }
      }, 1000)
    }
    return {
      deptDatas: [],
      treeValue: [],
      DRHA_EFaultModeTree_lables: [],
      depts: [],
      dialogFormVisible: false,
      dialogTransferVisible: false,
      dialogUserTransferVisible: false,
      organizationVisiable: false,
      userData: [],
      usersValue: '',
      page: { pageNo: 1, pageSize: 30, total: 0 },
      currentPageDatas: [], // 当前页数据
      currentDatas: [], // 当前数据
      sourceDatas: [], // 源数据,用于临时筛选数据
      currentChecks: [], // 左侧框当前已勾选的键数

      form: {
        fqr: '',
        title: '',
        kssj: '',
        jssj: '',
        sfgk: true,
        rcjb: '',
        sysOrganizations: '',
        sysUserMembers: '',
        content: '',
        desc: ''
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        },
        selectableRange: '00:00:00 - 23:59:59'
      },
      rules: {
        title: [{ required: true, message: '请输入日程标题', trigger: 'blur' }],
        kssj: [
          {
            required: true,
            message: '请选择开始时间',
            trigger: 'change'
          }
        ],
        jssj: [
          {
            required: true,
            validator: validateDate,
            message: '请选择结束时间且开始日期不能大于结束日期',
            trigger: 'change'
          }
        ],
        rcjb: [
          {
            required: true,
            message: '请选择日程级别',
            trigger: 'change'
          }
        ],
        content: [
          { required: true, message: '请描述日程内容', trigger: 'blur' }
        ]
      },

      defaultProps: {
        children: 'children',
        label: 'label'
      }
    }
  },

  methods: {
    watch: {
      'form.kssj'(selectTime) {
        this.$nextTick(() => {
          // const complaTime = this.findObject(this.option.column, 'kssj')
          // console.log("pickerOptions", kssj, selectTime);
          const date = new Date(
            new Date(selectTime).setHours(0, 0, 0, 0)
          ).getTime()

          const curTime = new Date().getTime()

          if (date < curTime) {
            const h = new Date(curTime).getHours()
            const m = new Date(curTime).getMinutes()
            console.log(
              h.toString() + ':' + m.toString() + ':' + '00' + '-' + '23:59:59'
            )
            /* kssj.pickerOptions.selectableRange =
              h.toString().padStart(2, '0') +
              ':' +
              m.toString().padStart(2, '0') +
              ':' +
              '00' +
              '-' +
              '23:59:59' */
            // console.log(complaTime.pickerOptions);
          } else {
            // kssj.pickerOptions.selectableRange = '00:00:00 - 23:59:59'
          }
        })
      }

    },
    openDialog(params) {
      this.dialogFormVisible = true
      if (params) {
        this.organizationVisiable = true
        // console.log(this.organizationVisiable + "-----");
      } else {
        this.organizationVisiable = false
        // console.log(this.organizationVisiable + "++++");
      }
    },
    // 分页change
    filterChange() {
      console.log()
    },
    handleCurrentChangeHandler(page_cur) {
      this.page.pageNo = page_cur

      // 先将选中的从当前数据过滤掉
      this.currentDatas = this.currentDatas.filter(
        function(value) {
          return !this.formDatas.river.includes(value.key)
        }.bind(this)
      )

      // 再将过滤好的当前数据选出指定页
      this.currentPageDatas = this.groupFunc(page_cur)

      // 再将选中的目标数组补给当前页变量，从而保证之前选的数据能在右边显示
      this.currentPageDatas = this.currentPageDatas.concat(
        this.sourceDatas.filter(
          function(val) {
            return this.formDatas.river.includes(val.key)
          }.bind(this)
        )
      )
    },
    filterMethod(query, item) {
      if (item.address != null) {
        return (
          item.name.indexOf(query) > -1 || item.address.indexOf(query) > -1
        ) // 对name和address字段同时校验
      } else {
        return item.name.indexOf(query) > -1 // 如果没有返回address 只对name校验
      }
    },
    // 获取所有选择项的label
    DRHA_EFaultModeTree_handleSelect(node, instanceId) {
      console.log('Select')

      this.DRHA_EFaultModeTree_lables.push(node.label)
    },
    // 删除已经选中的label
    DRHA_EFaultModeTree_handleDeSelect(node, instanceId) {
      console.log('DeSelect')

      for (let i = 0; i < this.DRHA_EFaultModeTree_lables.length; i++) {
        if (node.label === this.DRHA_EFaultModeTree_lables[i]) {
          this.DRHA_EFaultModeTree_lables.splice(i, 1)
        }
      }
    },

    // close() {
    //   this.$emit("close");
    // },
    getDeptDatas(node, resolve) {
      const sort = 'id,desc'
      const params = { sort: sort }
      if (typeof node !== 'object') {
        if (node) {
          params['blurry'] = node
        }
      } else if (node.level !== 0) {
        params['pid'] = node.data.id
      }
      setTimeout(() => {
        (async() => {
          try {
            const getdept = await getDepts(params)
            if (resolve) {
              resolve(getdept.content)
            } else {
              this.deptDatas = getdept.content
            }
            // console.log(this.depts);
          } catch (error) {
            console.log(error)
          }
        })()
        // getDepts(params).then(res => {
        //   if (resolve) {
        //     resolve(res.content);
        //   } else {
        //     this.deptDatas = res.content;
        //   }
        // });
      }, 100)
      // console.log(this.deptDatas);
    },

    // 获取部门数据
    getDepts() {
      (async() => {
        try {
          const getdepts = await getDepts({ enabled: true })

          this.depts = getdepts.content.map(function(obj) {
            if (!obj.hasChildren) {
              delete obj.children
            }
            return obj
          })
          console.log(this.depts)
          // this.nameTest = "2222";
        } catch (error) {
          console.log(error)
        }
      })()
    },

    // 获取弹窗内部门数据
    loadDepts({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        getDepts({ enabled: true, pid: parentNode.id }).then(res => {
          parentNode.children = res.content.map(function(obj) {
            if (!obj.hasChildren) {
              delete obj.children
            }
            // console.log(that.treeValue + "------");
            return obj
          })
          setTimeout(() => {
            callback()
          }, 200)
        })
      }
    },

    addSchedule(formName) {
      const userid = this.$store.getters.user.username
      this.form.fqr = userid
      this.form.sysOrganizations = this.treeValue.join(';')

      this.$refs[formName].validate(valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          (async() => {
            try {
              const result = await saveSchedule(this.form)
              console.log(result)

              if (result.state === 200) {
                loading.close()
                this.$message({
                  message: '保存成功',
                  type: 'success',
                  customClass: 'messageIndex'
                })
              }

              this.$emit('initData')
              this.dialogFormVisible = false
            } catch (error) {
              loading.close()
              this.$message({
                message: '保存失败！',
                type: 'warning',
                customClass: 'messageIndex'
              })
            }
          })()
        }
      })
    },

    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    getCurrentWeekMondayDate() {
      var now1 = new Date()
      var nowTime1 = now1.getTime()
      var day1 = now1.getDay() || 7 // 不加 || 7.周末会变成下周一
      var oneDayTime1 = 24 * 60 * 60 * 1000
      var MondayTime1 = nowTime1 - (day1 - 1) * oneDayTime1 // 显示周一
      // console.log(MondayTime1);
      var currentWeekMondayTime = new Date(MondayTime1)
      var year = currentWeekMondayTime.getFullYear()
      var month = currentWeekMondayTime.getMonth() + 1
      var day = currentWeekMondayTime.getDate()
      return year + '-' + month + '-' + day
    },
    validateDate(startTime, endTime, callback) {
      // 验证日期（判断结束日期是否大于开始日期）日期格式为YY—MM—DD
      if (!endTime) {
        return callback(new Error('结束时间不能为空'))
      }
      setTimeout(() => {
        if (startTime.length > 0 && endTime.length > 0) {
          var startTmp = startTime.split('-')
          var endTmp = endTime.split('-')
          var sd = new Date(startTmp[0], startTmp[1], startTmp[2])
          var ed = new Date(endTmp[0], endTmp[1], endTmp[2])
          if (sd.getTime() > ed.getTime()) {
            callback(new Error('开始日期不能大于结束日期'))
          } else {
            callback()
          }
        }
      }, 1000)
    }
  }
}
</script>

<style scoped>
::v-deep .vue-treeselect__control,
::v-deep .vue-treeselect__placeholder,
::v-deep .vue-treeselect__single-value {
  height: 30px;
  line-height: 30px;
}
.addsc ::v-deep .el-dialog {
  width: 60%;
}
.addsc ::v-deep .el-dialog__body {
  padding: 26px 40px;
}
.line {
  text-align: center;
}
.active {
  display: none;
}
.messageIndex {
  /* 设置的值一定要比2007大，因为dialog的层级是2007 */
  z-index: 9999 !important;
}
</style>
